import socket
import threading
import logging
from mon_center_utils import getDictDeeply, delDictDeeply
import mon_center_logger

logger = logging.getLogger('center.session')

session_info = {}
session_lock = threading.RLock()

def set_session(host, **kargs):
    session_lock.acquire()
    if not session_info.has_key(host):
        session_info[host] = {}
        session_info[host]['type'] = 'pm'
    this_session = session_info[host]
    for key, value in kargs.items():
        this_session[key] = value
    session_lock.release()
    logger.debug(repr(session_info))

def get_session(host, keys=None):
    session_lock.acquire()
    ret = None
    if session_info.has_key(host):
        try:
            if keys is None:
                ret = session_info[host]
            else:
                ret = getDictDeeply(session_info[host], keys)
        except KeyError, e:
            logger.error(repr(e))
            ret = None
    session_lock.release()
    return ret
        
def unset_session(host, keys=None):
    session_lock.acquire()
    if keys is None:
        del session_info[host]
    else:
        delDictDeeply(session_info[host], keys)
    session_lock.release()
    logger.debug(repr(session_info))

def getipbyid(id):
    ip = id
    return ip

def getidbyip(ip):
    type = getDictDeeply(session_info, [ip, 'type'])
    if type == 'pm':
        try:
            id = socket.gethostbyaddr(ip)[0]
        except socket.herror:
            id = ip
    else:
        id = getDictDeeply(session_info, [ip, 'id'])
    return id

